// components/the-chart/index.js
import { virtualHostConfig } from '@/behavior/virtualHost'
import { createUniqueId, debounce, isObject } from '@/utils/util'
import * as echarts from '@/components/ec-canvas/echarts';

Component({
  ...virtualHostConfig(),

  /**
   * 组件的属性列表
   */
  properties: {
    width: {
      type: String,
      value: '100%'
    },
    height: {
      type: String,
      value: '400rpx'
    },
    option: {
        type: Object,
        value: {}
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    chartId: `chart-canvas-dom-${ createUniqueId() }`,

    ec: {
      lazyLoad: true
    },
    isDisposed: false
  },

  observers: {
    'option.**': debounce(function () {
      this.setOption()
    }, 600)
  },

  lifetimes: {
    ready() {
      this._ecComponent = this.selectComponent(`#${this.data.chartId}`)
    },
    detached() {
      this.dispose()
    }
  },

  /**
   * 组件的方法列表
   */
  methods: {
    init() {
      return new Promise((resolve, reject) => {
        this._ecComponent.init((canvas, width, height, dpr) => {
          // 获取组件的 canvas、width、height 后的回调函数
          // 在这里初始化图表
          const chart = echarts.init(canvas, null, {
            width: width,
            height: height,
            devicePixelRatio: dpr // new
          });
          // setOption(chart);
    
          // 将图表实例绑定到 this 上，可以在其他成员函数（如 dispose）中访问
          this._chartObj = chart;
    
          this.setData({
            isDisposed: false
          }, () => {
            resolve()
          });
    
          // 注意这里一定要返回 chart 实例，否则会影响事件处理等
          return chart;
        });
      })
    },
    async setOption() {
        const { option } = this.properties
        if (!isObject(option) || Object.keys(option).length === 0) return

        if (!this._chartObj) {
          await this.init()
        }

        this._chartObj.setOption(option)
    },
    dispose() {
      if (this._chartObj) {
        this._chartObj.dispose();
      }
  
      this._chartObj = null
      this.setData({
        isDisposed: true
      });
    }
  }
})